package com.qjj.studydainty.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Base64;
import android.util.Patterns;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.EditorInfo;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.qjj.studydainty.Db.DBHelper;
import com.qjj.studydainty.Db.DbUtil;
import com.qjj.studydainty.DownloadThread;
import com.qjj.studydainty.widget.MyViewPager;
import com.qjj.studydainty.R;
import com.qjj.studydainty.adapter.WebFragmentPageAdapter;
import com.qjj.studydainty.entity.Marker;
import com.qjj.studydainty.entity.MyApplication;
import com.qjj.studydainty.fragment.WebViewFragment;
import com.qjj.studydainty.util.MenuUtil;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import static com.qjj.studydainty.entity.MyApplication.DESTROY_WEB_VIEW;
import static com.qjj.studydainty.entity.MyApplication.ERROR_WEB_VIEW;
import static com.qjj.studydainty.entity.MyApplication.HIDE_MENU;
import static com.qjj.studydainty.entity.MyApplication.HIDE_TOOLBAR;
import static com.qjj.studydainty.entity.MyApplication.PATH;
import static com.qjj.studydainty.entity.MyApplication.SHOW_TOOLBAR;
import static com.qjj.studydainty.entity.MyApplication.UPDATE_VIEWPAGER;
import static com.qjj.studydainty.entity.MyApplication.handler;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {


    private MyViewPager myViewPager;
    public static List<WebViewFragment> webViewFragmentList = new ArrayList<>();

    private static final int READ_WRITE_SDCARD_PERMISSION_REQUEST_CODE = 0;

    private long fileLength;
    public static String downloadFileName = null;

    public static String currentUrl = null;
    public static String currentTitle = null;

    private long pressBackButtonTime = 0;

    public static String mainPageUrl = "https://www.baidu.com";
    public static String searchUrl = "https://www.baidu.com/s?wd=";

    //通知相关
    private NotificationCompat.Builder builder;
    private NotificationManager notificationManager;
    private Notification notification;

    private WebView webView;
    private GridView menuGrid;
    private LinearLayout linearLayout;
    private EditText editTextUrl;
    private ImageButton imageButtonAddWebView;

    private WebFragmentPageAdapter webFragmentPageAdapter;

    /**
     * 向上滑出
     */
    private TranslateAnimation showAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
            Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
            1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
    /**
     * 向下滑出
     */
    private TranslateAnimation hideAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
            Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
            0.0f, Animation.RELATIVE_TO_SELF, 1.0f);


    private boolean showToolBarState = false;
    private boolean menuShowState = false;
    private Activity activity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initData();

        setTheme();

        setContentView(R.layout.activity_main);

        requestPermissions();

        initDb();

        initView();

        initMultiWindow();

        initNotification();

    }

    private void initData() {
        hideAction.setDuration(200);
        showAction.setDuration(200);

        handler = new MainActivityHandler();

        InputStream is = getResources().openRawResource(R.raw.night);
        byte[] buffer = new byte[0];
        try {
            buffer = new byte[is.available()];
            if (is.read(buffer) < 0) {
                Toast.makeText(MainActivity.this, "读取配置文件失败", Toast.LENGTH_SHORT).show();
            }
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        MyApplication.nightCode = Base64.encodeToString(buffer, Base64.NO_WRAP);
    }

    private void setTheme() {
        if (MyApplication.SHOW_THEME_FLAG == MyApplication.SHOW_WHITE_THEME_FLAG) {
            setTheme(R.style.DayTheme);
        } else if (MyApplication.SHOW_THEME_FLAG == MyApplication.SHOW_BLACK_THEME_FLAG) {
            setTheme(R.style.NightTheme);
        }
    }

    private void initMultiWindow() {
        final WebViewFragment webViewFragment = new WebViewFragment();
        webViewFragment.setHash(0);
        webViewFragmentList.add(webViewFragment);

        webFragmentPageAdapter = new WebFragmentPageAdapter(getSupportFragmentManager(), webViewFragmentList);
        myViewPager.setOffscreenPageLimit(5);
        myViewPager.setAdapter(webFragmentPageAdapter);

        myViewPager.setPageMargin(20);

        myViewPager.setOnLayoutClickListener(new MyViewPager.OnLayoutClickListener() {
            @Override
            public void onLayoutClick() {
                fullScreen();
                webView = webViewFragmentList.get(myViewPager.getCurrentItem()).getWebView();
                /*if (null != webView) {
                    webView.onResume();
                    webView.resumeTimers();
                }*/
            }
        });
    }

    private void initView() {
        myViewPager = findViewById(R.id.MyViewPager);

        imageButtonAddWebView = findViewById(R.id.imageButton_addWebview);
        imageButtonAddWebView.setOnClickListener(this);

        //导航栏
        linearLayout = findViewById(R.id.linearLayout);
        //导航栏控件
        editTextUrl = findViewById(R.id.editText_url);
        findViewById(R.id.imageButton_home).setOnClickListener(this);
        findViewById(R.id.imageButton_menu).setOnClickListener(this);
        findViewById(R.id.imageButton_window).setOnClickListener(this);
        findViewById(R.id.imageButton_open).setOnClickListener(this);

        editTextUrl.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                //当actionId == XX_SEND 或者 XX_DONE时都触发
                //或者event.getKeyCode == ENTER 且 event.getAction == ACTION_DOWN时也触发
                //注意，这是一定要判断event != null。因为在某些输入法上会返回null。
                if (actionId == EditorInfo.IME_ACTION_SEND
                        || actionId == EditorInfo.IME_ACTION_DONE
                        || (event != null && KeyEvent.KEYCODE_ENTER == event.getKeyCode() && KeyEvent.ACTION_DOWN == event.getAction())) {
                    //处理事件
                    openUrl();
                }
                return false;
            }
        });

        menuGrid = findViewById(R.id.menu);
        MenuUtil.showMenuDialog(MainActivity.this, menuGrid);
        menuGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            //监听menu按钮事件
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                switch (position) {
                    case 0:     //下载
                        hideMenu();
                        Intent intent = new Intent(MainActivity.this, ExplorerActivity.class);
                        startActivity(intent);
                        break;
                    case 1:     //夜间
                        hideMenu();
                        if (MyApplication.SHOW_THEME_FLAG == MyApplication.SHOW_BLACK_THEME_FLAG) {
                            MyApplication.SHOW_THEME_FLAG = MyApplication.SHOW_WHITE_THEME_FLAG;
                        } else if (MyApplication.SHOW_THEME_FLAG == MyApplication.SHOW_WHITE_THEME_FLAG) {
                            MyApplication.SHOW_THEME_FLAG = MyApplication.SHOW_BLACK_THEME_FLAG;
                        }
                        recreate();
                        webViewFragmentList = new ArrayList<>();
                        webFragmentPageAdapter.notifyDataSetChanged();
                        /*Intent mIntent = getIntent();
                        finish();
                        overridePendingTransition(0, 0);
                        startActivity(mIntent);*/
                        break;
                    case 2:     //刷新
                        hideMenu();
                        webView = webViewFragmentList.get(myViewPager.getCurrentItem()).getWebView();
                        if (null != webView) {
                            webView.reload();
                        }
                        break;
                    case 3:     //添加书签
                        hideMenu();
                        Marker marker = new Marker(currentTitle, currentUrl);
                        DbUtil.insertIntoMarker(MainActivity.this, marker);
                        Toast.makeText(MainActivity.this, "已添加", Toast.LENGTH_SHORT).show();
                        break;
                    case 4:     //历史
                        hideMenu();
                        Intent intent_history = new Intent(MainActivity.this, RecorderActivity.class);
                        startActivity(intent_history);
                        break;
                    case 5:     //退出
                        hideMenu();
                        finish();
                        break;
                    default:
                        break;
                }
            }
        });
    }

    private void initDb() {
        //创建辅助类对象
        DBHelper helper = new DBHelper(getApplicationContext());
        //调用getWritableDatabase()或getReadableDatabase()才会真正创建或打开
        SQLiteDatabase db = helper.getWritableDatabase();
        db.close(); //操作完成后关闭数据库连接
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.imageButton_open:
                openUrl();
                break;
            case R.id.imageButton_menu:
                if (!myViewPager.isFullScreen()) {
                    fullScreen();
                }
                if (menuShowState) {
                    hideMenu();
                } else {
                    menuShowState = true;
                    menuGrid.startAnimation(showAction);
                    menuGrid.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.imageButton_home:
                if (menuShowState) {
                    hideMenu();
                }
                if (!myViewPager.isFullScreen()) {
                    fullScreen();
                }
                webView = webViewFragmentList.get(myViewPager.getCurrentItem()).getWebView();
                if (null != webView) {
                    webView.loadUrl(mainPageUrl);
                }
                break;
            case R.id.imageButton_window:
                if (menuShowState) {
                    hideMenu();
                }
                if (myViewPager.isFullScreen()) {
                    exitFullScreen();
                } else {
                    fullScreen();
                }
                break;
            case R.id.imageButton_addWebview:
                addWebView();
                break;
            default:
                break;
        }
    }

    private void openUrl() {
        if (menuShowState) {
            hideMenu();
        }
        if (!myViewPager.isFullScreen()) {
            fullScreen();
        }
        String url = editTextUrl.getText().toString();

        if (!url.startsWith("https://")) {
            url = "https://" + url;
        }
        webView = webViewFragmentList.get(myViewPager.getCurrentItem()).getWebView();
        if (null != webView) {
            if (Patterns.WEB_URL.matcher(url).matches()) {
                webView.loadUrl(editTextUrl.getText().toString());
            } else {
                webView.loadUrl(searchUrl + editTextUrl.getText().toString());
            }
        }
    }

    private void exitFullScreen() {
        imageButtonAddWebView.setVisibility(View.VISIBLE);
        myViewPager.setFullScreen(false);
        myViewPager.animate().scaleX(0.65f).scaleY(0.65f).setDuration(400).start();

    }

    private void fullScreen() {
        myViewPager.setFullScreen(true);
        imageButtonAddWebView.setVisibility(View.GONE);
        myViewPager.animate().scaleX(1f).scaleY(1f).setDuration(400).start();
    }

    //初始化通知
    private void initNotification() {

        String channelId = createNotificationChannel(this);
        if (null == channelId) {
            Toast.makeText(MainActivity.this, "发送通知失败", Toast.LENGTH_SHORT).show();
            return;
        }

        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        builder = new NotificationCompat.Builder(this, channelId);
        //设置通知标题
        builder.setContentTitle("正在下载")
                .setSmallIcon(R.drawable.browser1)
                //设置通知的大图标
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.browser1))
                //设置通知的提醒方式： 呼吸灯
                .setDefaults(Notification.DEFAULT_LIGHTS)
                //设置通知的优先级：最大
                .setPriority(NotificationCompat.PRIORITY_MAX)
                //设置通知被点击一次是否自动取消
                .setAutoCancel(false)
                .setContentText("下载进度:" + "0% " + "0MB")
                //构建通知对象
                .setProgress(100, 0, false);
        notification = builder.build();

    }

    //创建通知频道
    public static String createNotificationChannel(Context context) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String channelId = "downloading";
            CharSequence channelName = "下载进度";
            String channelDescription = "显示下载进度";
            int channelImportance = NotificationManager.IMPORTANCE_DEFAULT;

            NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, channelImportance);
            // 设置描述 最长30字符
            notificationChannel.setDescription(channelDescription);
            // 该渠道的通知是否使用震动
            notificationChannel.enableVibration(false);
            // 设置显示模式
            notificationChannel.setLockscreenVisibility(NotificationCompat.VISIBILITY_PUBLIC);

            NotificationManager notificationManager =
                    (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

            if (null == notificationManager) {
                return null;
            }

            notificationManager.createNotificationChannel(notificationChannel);

            return channelId;
        } else {
            return null;
        }
    }

    private void requestPermissions() {
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            // 申请读写内存卡内容的权限
            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, READ_WRITE_SDCARD_PERMISSION_REQUEST_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == READ_WRITE_SDCARD_PERMISSION_REQUEST_CODE) {
            if (!(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED)) {
                Toast.makeText(this, "读写内存卡内容权限被拒绝", Toast.LENGTH_SHORT).show();
            }
        }
    }

    //隐藏弹出式菜单栏
    private void hideMenu() {
        menuGrid.startAnimation(hideAction);
        menuGrid.setVisibility(View.INVISIBLE);
        menuShowState = false;
    }

    @SuppressLint("HandlerLeak")
    public class MainActivityHandler extends Handler {
        @Override
        public void handleMessage(@NonNull Message message) {
            switch (message.what) {
                case DownloadThread.SDCARD_NO_PERMISSION:
                    Toast.makeText(MainActivity.this, "无文件读写权限", Toast.LENGTH_SHORT).show();
                    break;
                case MyApplication.FILE_LENGTH:
                    fileLength = (long) message.obj;
                    break;
                case MyApplication.ACTIVITY_OBJECT:
                    activity = (Activity) message.obj;
                    break;
                case MyApplication.OPEN_URL_IN_NEW_WINDOW:
                    if (null != activity) {
                        activity.finish();
                    }
                    String url = (String) message.obj;
                    addWebView(url);
                    break;
                case DownloadThread.DOWNLOAD_SUCCESS:
                    downloadFileName = (String) message.obj;

                    builder.setContentTitle("下载完成");
                    builder.setProgress(100, 100, false);
                    builder.setContentText("下载进度:100% 下载大小：" + fileLength / 1048576 + "MB");
                    Intent intent = getOpenFileIntent(downloadFileName);
                    if (null == intent) {
                        break;
                    }
                    PendingIntent pendingIntent = android.app.PendingIntent.getActivity(MainActivity.this, 0, intent, 0);
                    builder.setContentIntent(pendingIntent);

                    notification = builder.build();
                    notificationManager.notify(1, notification);
                    Toast.makeText(MainActivity.this, "下载成功", Toast.LENGTH_SHORT).show();
                    break;
                case DownloadThread.DOWNLOAD_START:
                    Toast.makeText(MainActivity.this, "文件长度：" + message.obj + "MB,开始下载", Toast.LENGTH_SHORT).show();
                    break;
                case DESTROY_WEB_VIEW:
                    onWebFragmentDelete();

                    //myViewPager.scrollTo(0,0);
                    break;
                case HIDE_MENU:
                    if (menuShowState) {
                        hideMenu();
                    }
                    break;
                case HIDE_TOOLBAR:
                    if (showToolBarState) {
                        linearLayout.startAnimation(hideAction);
                        linearLayout.setVisibility(View.INVISIBLE);
                        showToolBarState = false;
                    }
                    break;
                case SHOW_TOOLBAR:
                    if (showToolBarState) {
                        return;
                    }
                    linearLayout.startAnimation(showAction);
                    linearLayout.setVisibility(View.VISIBLE);
                    showToolBarState = true;
                    break;
                case DownloadThread.DOWNLOAD_PROGRESSING:
                    long downloadLength = (long) message.obj;
                    int percent = (int) (downloadLength * 100 / fileLength);
                    int fileSize = (int) (downloadLength / 1048576f);

                    builder.setProgress(100, percent, false);
                    builder.setContentText("下载进度:" + percent + "% 下载大小：" + fileSize + "MB");
                    notification = builder.build();
                    notificationManager.notify(1, notification);
                    break;
                case ERROR_WEB_VIEW:
                    View view = View.inflate(MainActivity.this, R.layout.error, null);
                    final PopupWindow popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
                    popupWindow.setOutsideTouchable(true);

                    View viewParent = View.inflate(MainActivity.this, R.layout.activity_main, null);

                    TextView t = view.findViewById(R.id.textView_error);
                    t.setText(message.obj.toString());
                    view.findViewById(R.id.button_confirm).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            popupWindow.dismiss();
                        }
                    });

                    popupWindow.showAtLocation(viewParent, Gravity.CENTER, 0, 0);
                    //Toast.makeText(MainActivity.this, (String) message.obj, Toast.LENGTH_SHORT).show();
                    break;
                case UPDATE_VIEWPAGER:
                    if (webViewFragmentList.size() > 0) {
                        View selectedView = webViewFragmentList.get(myViewPager.getCurrentItem()).getFrameLayout();
                        selectedView.setAlpha(1f);
                        selectedView.setScaleY(1f);
                        selectedView.setScaleX(1f);
                    }
                    break;
                default:
                    break;
            }
        }

    }

    private void addWebView(String url) {
        if (webViewFragmentList.size() >= 6) {
            Toast.makeText(MainActivity.this, "已达到最大窗口数量，请关闭一些后重试", Toast.LENGTH_SHORT).show();
            return;
        }
        /*//暂停其他webview
        for (WebViewFragment webViewFragment : webViewFragmentList) {
            webViewFragment.getWebView().onPause();
            webViewFragment.getWebView().pauseTimers();
        }*/

        WebViewFragment fragment;
        if (null != url) {
            fragment = new WebViewFragment(url);
        } else {
            fragment = new WebViewFragment();
        }
        fragment.setHash(webViewFragmentList.size());
        webViewFragmentList.add(fragment);
        webFragmentPageAdapter.notifyDataSetChanged();

        myViewPager.setCurrentItem(webViewFragmentList.size() - 1);

        myViewPager.setFullScreen(true);
        myViewPager.animate().scaleX(1f).scaleY(1f).setDuration(400).start();
        imageButtonAddWebView.setVisibility(View.GONE);
    }

    private void addWebView() {
        addWebView(null);
    }

    public void onWebFragmentDelete() {
        //删除动画
        View selectedView = webViewFragmentList.get(myViewPager.getCurrentItem()).getFrameLayout();
        Animation animation = new TranslateAnimation(0, 0, 0, -2500);
        animation.setDuration(400);
        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                webViewFragmentList.remove(myViewPager.getCurrentItem());
                webFragmentPageAdapter.setDeletePosition(myViewPager.getCurrentItem());
                webFragmentPageAdapter.notifyDataSetChanged();

                handler.sendEmptyMessage(UPDATE_VIEWPAGER);

                /*webView = webViewFragmentList.get(myViewPager.getCurrentItem()).getWebView();
                if (null != webView) {
                    webView.onResume();
                    webView.resumeTimers();
                }*/

                if (webViewFragmentList.size() == 0) {
                    addWebView();
                }
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        selectedView.startAnimation(animation);
    }

    public Intent getOpenFileIntent(String downloadFileName) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        File fileDir = new File(PATH);
        if (!fileDir.exists()) {
            if (!fileDir.mkdirs()) {
                return null;
            }
        }
        if (downloadFileName == null) {
            return new Intent();
        }
        File file = new File(PATH, downloadFileName);

        Uri uri;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            uri = Uri.fromFile(file);
        } else {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            uri = FileProvider.getUriForFile(MainActivity.this, getPackageName() + ".provider", file);
        }
        intent.setData(uri);
        return intent;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            webView = webViewFragmentList.get(myViewPager.getCurrentItem()).getWebView();
            if (webView != null) {
                if (webView.canGoBack()) {
                    webView.goBack();
                    return false;
                }
            }
            if (Calendar.getInstance().getTimeInMillis() - pressBackButtonTime <= 1000) {
                finish();
            } else {
                Toast.makeText(this, "双击退出", Toast.LENGTH_SHORT).show();
            }
            pressBackButtonTime = Calendar.getInstance().getTimeInMillis();
            return false;
        }

        return super.onKeyDown(keyCode, event);

    }

    public void closeNotification() {
        if (notificationManager != null) {
            notificationManager.cancel(1);
        }
    }

    @Override
    protected void onDestroy() {
        DownloadThread.cancelThread();
        closeNotification();

        super.onDestroy();
    }

}
